package com.zf.wms.business.datasources;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 动态数据源
 * @Author: Mine
 * @CreateDate: 2019/2/28 10:17
 * @email 1943511692@qq.com
 * @Version: 1.0.0
 */
public class DynamicDataSource extends AbstractRoutingDataSource {
    private static final ThreadLocal<DatasourceTypeEnum> CONTEXTHOLDER = new ThreadLocal<>();

    public DynamicDataSource(DataSource defaultTargetDataSource, Map<DatasourceTypeEnum, DataSource> targetDataSources) {
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        super.setTargetDataSources(new HashMap<>(targetDataSources));
        super.afterPropertiesSet();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return getDataSource();
    }

    public static void setDataSource(DatasourceTypeEnum dataSource) {
    	CONTEXTHOLDER.set(dataSource);
    }

    public static DatasourceTypeEnum getDataSource() {
        return CONTEXTHOLDER.get();
    }

    public static void clearDataSource() {
    	CONTEXTHOLDER.remove();
    }

}
